import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleChatServer {
    private static final int MAX_CLIENTS = 1000;
    private static final int SERVER_PORT = 7711;

    private static ServerSocket serverSocket;
    private static List<Client> clients = new ArrayList<>();

    public static void main(String[] args) {
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            System.out.println("Server is running on port " + SERVER_PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                Client client = new Client(clientSocket);
                clients.add(client);

                System.out.println("New client connected: " + clientSocket.getInetAddress());

                Thread clientThread = new Thread(client);
                clientThread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Client implements Runnable {
        private Socket socket;
        private PrintWriter out;
        private String nickname;

        Client(Socket socket) {
            this.socket = socket;
            try {
                out = new PrintWriter(socket.getOutputStream(), true);
                nickname = "user:" + socket.getPort();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                out.println("Welcome to Simple Chat! Use /nick <nick> to set your nickname.");

                String message;
                while ((message = in.readLine()) != null) {
                    if (message.startsWith("/nick ")) {
                        setNickname(message.substring(6));
                    } else {
                        broadcast(nickname + "> " + message);
                    }
                }

                // Client disconnected
                clients.remove(this);
                socket.close();
                broadcast(nickname + " has left the chat.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void setNickname(String newNickname) {
            String oldNickname = nickname;
            nickname = newNickname;
            out.println("Your nickname has been changed to " + nickname);
            broadcast(oldNickname + " has changed their nickname to " + nickname);
        }

        private void broadcast(String message) {
            for (Client client : clients) {
                if (client != this) {
                    client.sendMessage(message);
                }
            }
        }

        private void sendMessage(String message) {
            out.println(message);
        }
    }
}
